package com.hmall.order.mq;

import com.hmall.feign.client.ItemClient;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class OrderLister {

    @Resource
    private IOrderService orderService;

    @Resource
    private IOrderDetailService orderDetailService;

    @Resource
    private ItemClient itemClient;

    /**
     * 监听死信队列
     *
     * @param orderId 订单ID
     */
    @RabbitListener(queues = QueueConfig.DLX_QUEUE_NAME)
    public void expireOrder(String orderId) {
        log.info("{} 订单过期了!", orderId);
        Order order = orderService.getById(orderId);
        // 订单未支付
        if (1 == order.getStatus()) {
            OrderDetail orderDetail = orderDetailService.getById(orderId);
            // 获取商品购买数量
            Integer orderNum = orderDetail.getNum();
            // 修改订单状态为交易取消
            orderService.update().set("status", 5).eq("id", orderId).update();
            // 恢复商品数量
            itemClient.addStock(Long.valueOf(orderId), orderNum);
        }

    }
}
